# Read the Excel file
pareto_norm_final <- read_excel("QWTB_pareto_0527.xlsx")

# Extract sample information
sample_names <- pareto_norm_final$Sample
groups <- pareto_norm_final$Group

# Extract feature matrix (exclude Sample and Group columns)
X <- pareto_norm_final[, -c(1, 2)]
X <- as.matrix(X)

# Set row names as sample names
rownames(X) <- sample_names

# Convert groups to factor
Y <- as.factor(groups)

# Perform PLS-DA
plsda_result <- plsda(X, Y, ncomp = 3)

# Extract scores for plotting
scores <- plsda_result$variates$X
scores_df <- data.frame(
  Sample = sample_names,
  Group = groups,
  PC1 = scores[, 1],
  PC2 = scores[, 2],
  PC3 = if(ncol(scores) >= 3) scores[, 3] else rep(0, nrow(scores))
)

# Calculate explained variance
explained_var <- plsda_result$explained_variance$X

# Create PLS-DA score plot (PC1 vs PC2)
p1 <- ggplot(scores_df, aes(x = PC1, y = PC2, color = Group, label = Sample)) +
  geom_point(size = 3, alpha = 0.8) +
  geom_text(vjust = -0.5, hjust = 0.5, size = 3) +
  labs(
    title = "PLS-DA Score Plot",
    x = paste0("PC1 (", round(explained_var[1] * 100, 1), "% variance)"),
    y = paste0("PC2 (", round(explained_var[2] * 100, 1), "% variance)")
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    legend.title = element_text(size = 12),
    legend.text = element_text(size = 10),
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 10)
  ) +
  scale_color_brewer(type = "qual", palette = "Set1")

# Display the plot
print(p1)
